package org.brisling.medical.queryService;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.brisling.authorize.shiro.ShiroSecurityService;
import org.brisling.base.domain.ListDomain;
import org.brisling.base.service.AbstractBaseQueryService;
import org.brisling.common.ConstSysParam;
import org.brisling.common.exception.DangerousOperatorException;
import org.brisling.common.util.DateUtil;
import org.brisling.medical.domain.CheckResult;
import org.brisling.medical.service.CheckResultService;
import org.brisling.sysman.queryService.QueryDictionaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 * <p>Title: QueryAntiDrugdoseService</p>
 * <p>Description: 抗菌药物使用率查询service</p>
 * <p>Company: tongking</p>
 * @author trastor
 * @since 1.0
 * @version 1.0
 * @date 2016年7月20日 下午10:00:47
 */
@RestController
@RequestMapping("/checkResult/query")
public class QueryCheckResultService extends AbstractBaseQueryService<CheckResult>{
	
	@Autowired
	private CheckResultService qrService;
	
	@Autowired
	private QueryDictionaryService qryDictionaryService;
	
	@Autowired
	private ShiroSecurityService shiroSecurityService;
	@Autowired
	private QueryDictionaryService dicService;
	
	public QueryCheckResultService(){
		this.moduleName = ConstSysParam.MODULE_CHECK_RESULT;
		this.subSystem = ConstSysParam.SUBSYSTEM_MEDICAL;
		this.tableName = ConstSysParam.VIEW_PREFIX +this.moduleName;
		this.clazz = CheckResult.class;
		typeMap = this.getTypeMap(clazz);
	}
	
	@PersistenceContext(unitName=ConstSysParam.SUBSYSTEM_SYSMAN)
	@Autowired
	protected void setEntityManager(EntityManager entityManager){
		this.entityManager = entityManager;		
	}
	
	@RequestMapping("/mainPage.action")
	public ModelAndView getMainPage(){
		return this.getBizMainPage();
	}
	
	/* (non-Javadoc)
	 * @see org.brisling.service.sysman.DepartmentServiceInf#getEditPage()
	 */
	@RequestMapping("/editPage.action")
	public ModelAndView getEditPage(){
		return this.getBizEditPage();
	}
	
	@RequestMapping("/getListDomain.action")
	public ListDomain<CheckResult> getListDomain(@RequestBody(required=false) String body){		
		
		Map<String,Object> map = this.getBodyParam(body);
		String userid = shiroSecurityService.getCurrentUserIdentify();
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_medical_all")){			
			addJobDeptConditionToMap(userid,map,"dept_code");			
			//查找科室数据		
		}
		//查询表
		return super.getListDomainByConditionAndOrder(null, map, typeMap, orderMap, true);
		
		
	}
	
	/**
	 * 查询实时数据
	 * @param body
	 * @return
	 */
	@RequestMapping("/getRealTimeListDomain.action")
	public ListDomain<CheckResult> getRealTimeListDomain(@RequestBody(required=false) String body){		
		Map<String,Object> paramMap = this.getBodyParam(body);
		
		String[] monitorDate = super.getMonitorDate(paramMap);
		if(monitorDate!=null && monitorDate.length>1){			
			
			String start = monitorDate[0];
			String end = monitorDate[1];
			String year_month = monitorDate[2];
			List<CheckResult> inlists =countMedicalInpatient (year_month,start,end,null);
			
			
			if(inlists!=null ){				
				qrService.save(inlists);
				return super.getListDomainByConditionAndOrderUseTable(body, typeMap, orderMap,true);
			}					
			
		}
		//查询表
		
		return new ListDomain<CheckResult>();
	}
	
	/**
	 * 执行自动统计
	 */
	
	/**
	 * 统计住院患者抗菌药物使用情况
	 * @param year_month
	 * @param startDate
	 * @param endDate
	 * @param countType	0,期间出院病人;1,期间在院病人
	 * @return
	 */
	public List<CheckResult> countMedicalInpatient(String year_month,String startDate ,String endDate,String countType){
		
		
		//出院病人
		String _count_type = "0";
		
		//在院病人统计语句
		String sqlins= "anti_dose_drug_inpatient_in";
		
		//出院病人统计语句
		String sqlouts= "anti_dose_drug_inpatient_out";
		_count_type = countType==null?_count_type:countType;
		
		String sqlids = null;
		
		if(_count_type.compareTo("0")==0){			
			sqlids = sqlouts;
		}else{
			sqlids = sqlins;
		}
		//统计全院数据-住院
		
		
		
		String sql = qryDictionaryService.getSqlByBizcode(sqlids);
		List<CheckResult> lists = new ArrayList<CheckResult>();
		if(sql!=null){
			sql =String.format(sql, year_month,ConstSysParam.VIEW_INPATIENT_ITEM,startDate,endDate,ConstSysParam.MODULE_DRUG);
			//所有数据
			lists = super.getAllList(sql);
		}
				
		
		return lists;
		
	}
	
		
	/**
	 * 根据用户id查找用户信息
	 * @param id	用户id
	 * @return 用户信息记录 
	 */
	@RequestMapping("/getOne.action")
	public CheckResult getOne(@RequestParam(value="id",required=false) Long id){
				
		return super.getOne(id);
	}
	
	/**
	 * 根据用户唯一编码查找用户信息
	 * @param identify	用户唯一编码
	 * @return 用户信息记录
	 */
	@RequestMapping("/getOneByIdentify.action")
	public CheckResult getOneByIdentify(@RequestParam(value="identify",required=false) String identify){	
		return super.getOneByIdentify(identify);
	}
	
	
	/**
	 * 指定更新年月数据
	 * @param year
	 * @param month
	 */
	public void pointdate (int year,int month){
		String tmpdate [] = DateUtil.getMonthDay(year, month);
		save (tmpdate);
	}
	/**
	 * 自动保存用药记录
	 * @param userId
	 */
	public void autosave (){
		String tmpdate[] = DateUtil.getYestodayMonthDay();
		save (tmpdate);
	}
	
	
	/**
	 * 保存数据
	 */
	private void save (String tmpdate[]){
		List <CheckResult> lists = this.getCheckResult("Check_Result",tmpdate);
		List <CheckResult> oldlist = this.getoldlist (tmpdate);
		LinkedHashMap<Long,CheckResult> lmap = new LinkedHashMap<Long,CheckResult>();
		
		if (oldlist!=null){
			for (CheckResult e: oldlist){
				lmap.put(e.getId(), e);
			}
			for (CheckResult i:lists){
				CheckResult old = lmap.get(i.getId());
				if (old!=null){
					i.setId(old.getId());
				}
			}
		}
		qrService.save(lists);
	}
	
	private List<CheckResult> getoldlist(String tmpdate[]) {
		
		String sql = String.format("select * from MEDICAL_DRUG_COUNTING f where F.MONITOR_YEAR_MONTH ='%1$s'", tmpdate[2]);
		return super.getAllList(sql);
	}
	
	private List<CheckResult> getCheckResult(String bizcode,String tmpdate[]) {
		String sql = dicService.getSqlByBizcode(bizcode);
		
		sql = String.format(sql,tmpdate[0],tmpdate[1]);
		try {
			return super.getClassedAllList(sql, CheckResult.class);
		} catch (DangerousOperatorException e) {
			e.printStackTrace();
		}
		return null;
	}
}
